<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link href='/css/styles.css' rel='stylesheet' type='text/css' />
    <link href='/images/favicon.png' rel='shortcut icon' />
    <script src='/js/jquery.min.1.4.js'></script>
    <script src='/js/app.js'></script>
    <script src='/js/common.js'></script>
    
    <meta content='width=device-width, minimum-scale=1.0, maximum-scale=1.0' name='viewport' />
    <title>redis - 命令</title>
	<meta http-equiv="description" content="redis中文资料站，下载安装redis，查找redis常用命令（commands），选择适合的redis客户端方式，配置redis主从（master-slave），阅读redis官方文档，社区里了解更多redis信息，提交redis的bug。" />
	
  </head>
  <body class=''>
    <script src='/js/head.js'></script>
    <div class='text'>
      <h1 class='command'>
        <span id='command_name_span' class='name'></span>
        <span id='command_args_span' class='arg'></span>
      </h1>
      <article>
      	<aside>
        	<script type='text/javascript'>showCmdURL();</script>
        </aside>
        
        <div class='metadata'>
          <p><strong>加入版本 <span id='command_ver_span'></span>。</strong></p>
          <p><strong>时间复杂度：</strong> O(N+M*log(M)) where N is the number of elements in the list or set to sort, and M the number of returned elements. When the elements are not sorted, complexity is currently O(N) as there is a copy step that will be avoided in next releases。</p>
        </div>
        
        <p>Returns or stores the elements contained in the <a href="/topics/data-types.html#lists">list</a>, <a href="/topics/data-types.html#set">set</a> or
        <a href="/topics/data-types.html#sorted-sets">sorted set</a> at <code>key</code>.
        By default, sorting is numeric and elements are compared by their value
        interpreted as double precision floating point number.
        This is <a href="/commands/sort.html">SORT</a> in its simplest form:</p>
        
        <pre><code>SORT mylist&#x000A;</code></pre>
        
        <p>Assuming <code>mylist</code> is a list of numbers, this command will return the same list
        with the elements sorted from small to large.
        In order to sort the numbers from large to small, use the <code>DESC</code> modifier:</p>
        
        <pre><code>SORT mylist DESC&#x000A;</code></pre>
        
        <p>When <code>mylist</code> contains string values and you want to sort them
        lexicographically, use the <code>ALPHA</code> modifier:</p>
        
        <pre><code>SORT mylist ALPHA&#x000A;</code></pre>
        
        <p>Redis is UTF-8 aware, assuming you correctly set the <code>!LC_COLLATE</code> environment
        variable.</p>
        
        <p>The number of returned elements can be limited using the <code>LIMIT</code> modifier.
        This modifier takes the <code>offset</code> argument, specifying the number of elements to
        skip and the <code>count</code> argument, specifying the number of elements to return from
        starting at <code>offset</code>.
        The following example will return 10 elements of the sorted version of <code>mylist</code>,
        starting at element 0 (<code>offset</code> is zero-based):</p>
        
        <pre><code>SORT mylist LIMIT 0 10&#x000A;</code></pre>
        
        <p>Almost all modifiers can be used together.
        The following example will return the first 5 elements, lexicographically sorted
        in descending order:</p>
        
        <pre><code>SORT mylist LIMIT 0 5 ALPHA DESC&#x000A;</code></pre>
        
        <h2>Sorting by external keys</h2>
        
        <p>Sometimes you want to sort elements using external keys as weights to compare
        instead of comparing the actual elements in the list, set or sorted set.
        Let&#39;s say the list <code>mylist</code> contains the elements <code>1</code>, <code>2</code> and <code>3</code> representing
        unique IDs of objects stored in <code>object_1</code>, <code>object_2</code> and <code>object_3</code>.
        When these objects have associated weights stored in <code>weight_1</code>, <code>weight_2</code> and
        <code>weight_3</code>, <a href="/commands/sort.html">SORT</a> can be instructed to use these weights to sort <code>mylist</code> with
        the following statement:</p>
        
        <pre><code>SORT mylist BY weight_*&#x000A;</code></pre>
        
        <p>The <code>BY</code> option takes a pattern (equal to <code>weight_*</code> in this example) that is
        used to generate the keys that are used for sorting.
        These key names are obtained substituting the first occurrence of <code>*</code> with the
        actual value of the element in the list (<code>1</code>, <code>2</code> and <code>3</code> in this example).</p>
        
        <h2>Skip sorting the elements</h2>
        
        <p>The <code>BY</code> option can also take a non-existent key, which causes <a href="/commands/sort.html">SORT</a> to skip
        the sorting operation.
        This is useful if you want to retrieve external keys (see the <code>GET</code> option
        below) without the overhead of sorting.</p>
        
        <pre><code>SORT mylist BY nosort&#x000A;</code></pre>
        
        <h2>Retrieving external keys</h2>
        
        <p>Our previous example returns just the sorted IDs.
        In some cases, it is more useful to get the actual objects instead of their IDs
        (<code>object_1</code>, <code>object_2</code> and <code>object_3</code>).
        Retrieving external keys based on the elements in a list, set or sorted set can
        be done with the following command:</p>
        
        <pre><code>SORT mylist BY weight_* GET object_*&#x000A;</code></pre>
        
        <p>The <code>GET</code> option can be used multiple times in order to get more keys for every
        element of the original list, set or sorted set.</p>
        
        <p>It is also possible to <code>GET</code> the element itself using the special pattern <code>#</code>:</p>
        
        <pre><code>SORT mylist BY weight_* GET object_* GET #&#x000A;</code></pre>
        
        <h2>Storing the result of a SORT operation</h2>
        
        <p>By default, <a href="/commands/sort.html">SORT</a> returns the sorted elements to the client.
        With the <code>STORE</code> option, the result will be stored as a list at the specified
        key instead of being returned to the client.</p>
        
        <pre><code>SORT mylist BY weight_* STORE resultkey&#x000A;</code></pre>
        
        <p>An interesting pattern using <code>SORT ... STORE</code> consists in associating an
        <a href="/commands/expire.html">EXPIRE</a> timeout to the resulting key so that in applications where the result
        of a <a href="/commands/sort.html">SORT</a> operation can be cached for some time.
        Other clients will use the cached list instead of calling <a href="/commands/sort.html">SORT</a> for every
        request.
        When the key will timeout, an updated version of the cache can be created by
        calling <code>SORT ... STORE</code> again.</p>
        
        <p>Note that for correctly implementing this pattern it is important to avoid
        multiple clients rebuilding the cache at the same time.
        Some kind of locking is needed here (for instance using <a href="/commands/setnx.html">SETNX</a>).</p>
        
        <h2>Using hashes in <code>BY</code> and <code>GET</code></h2>
        
        <p>It is possible to use <code>BY</code> and <code>GET</code> options against hash fields with the
        following syntax:</p>
        
        <pre><code>SORT mylist BY weight_*-&gt;fieldname GET object_*-&gt;fieldname&#x000A;</code></pre>
        
        <p>The string <code>-&gt;</code> is used to separate the key name from the hash field name.
        The key is substituted as documented above, and the hash stored at the resulting
        key is accessed to retrieve the specified hash field.</p>
        
        <h2>Return value</h2>
        
        <p><a href="/topics/protocol.html#multi-bulk-reply">Multi-bulk reply</a>: list of sorted elements.</p>
        
      </article>
    </div>
    
    <script type='text/javascript'>startShow();</script>
    <div class='text' id='comments'>
      <div id='disqus_thread'></div>
      <script type='text/javascript'>
        //<![CDATA[
          var disqus_shortname = 'rediscn';
          
          // The following are highly recommended additional parameters. Remove the slashes in front to use.
          var disqus_identifier = 'command_'+curCommandObj.key;
          var disqus_url = curCommandObj.getdisqusUrl();
          
          /* * * DON'T EDIT BELOW THIS LINE * * */
          (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
              dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
              (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
          })();
        //]]>
      </script>
      <a class='dsq-brlink' href='http://disqus.com'>
        Comments powered by
        <span class='logo-disqus'>
          Disqus
        </span>
      </a>
    </div>

    
    <script src='/js/foot.js'></script>
    
  </body>
</html>
